<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\model\ClientAccountModel;
use app\model\CrontabTaskModel;
use app\model\ProjectAccountModel;
use app\model\ProjectModel;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

// 已测试
class ProjectNotAccountWork extends BaseWork implements DailyStatWork
{
    public const DEFAULT_PROJECT_ID = 43;

    public string $tag;

    /**
     * 设置任务标识.
     * @param mixed $tag
     */
    public function setTag($tag = ''): bool
    {
        if (! is_null($tag)) {
            $this->tag = strval($tag);
        }
        return true;
    }

    /**
     * 获取任务标识.
     */
    public function getTag(): string
    {
        return $this->tag;
    }

    /**
     * 获取脚本名.
     */
    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            //            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    // 已测试
    protected function configure()
    {
        // 指令配置
        $this->setName('project_not_account_work');
        $this->setDescription('未分配账户入默认项目');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $output->writeln('=======未分配账户入默认项目开始' . date('Y-m-d H:i:s', time()) . '=======');
        $allAcount = ClientAccountModel::alias('a')
            ->leftJoin(['habo_project_account' => 'b'], 'a.id=b.account_id')
            ->where('a.account_type', 1)
            ->where('a.company_id', 1)
            ->whereNull('b.id')
            ->field('a.id,a.client_id')
            ->select()->toArray();
        if ($allAcount) {
            foreach ($allAcount as $v) {
                $data = [
                    'project_id' => self::DEFAULT_PROJECT_ID,
                    'client_id' => $v['client_id'],
                    'account_id' => $v['id'],
                ];
                ProjectAccountModel::create($data);
            }
        }

        $output->writeln('=======未分配账户入默认项目结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }
}
